package com.example.springbootjwtexample.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootjwtexample.koal.ByteUtil;
import com.example.springbootjwtexample.koal.EncryptUtil;
import com.example.springbootjwtexample.koal.SSORequest;
import com.example.springbootjwtexample.utils.AgentComponent;
import com.example.springbootjwtexample.utils.JWTParseUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/gateway")
public class GatewayController {

    private String nonce = RandomStringUtils.randomNumeric(16);
    private String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
    private String aid = "jnzhnbhxayz";
    private String key = "c909a2a828ececa94d97f68de98321a9";
    @GetMapping(value = "/login_with_Webcall")
    public void loginWithWebCall(HttpServletResponse response,@RequestParam("auth_request") final String authRequest) throws IOException {
        System.err.println("authRequest=" + authRequest);

        if (StringUtils.isNotBlank(authRequest)) {
            JSONObject payloadJSON = JWTParseUtil.jwtParser(authRequest).getRight();
            String url = payloadJSON.getString("url");
            Map<String,Object> authResponseMap = new HashMap<>();
            authResponseMap.put("token","5621683cb648c2c3014d7c5025de0267");
            authResponseMap.put("expired", System.currentTimeMillis());
            SSORequest ssoRequest = new SSORequest(authResponseMap,AgentComponent.AGENT_ID,AgentComponent.AGENT_KEY);
            String authResponseToken = ssoRequest.toString();
            String redirectUrl = url.concat("?auth_response=" + authResponseToken);
            System.err.println(redirectUrl);
            response.sendRedirect(redirectUrl);
        }

    }

    @GetMapping(value = "/token_verify",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> tokenVerify(@RequestParam("tokenVerify_request") final String tokenVerifyRequest) throws UnsupportedEncodingException {
        JSONObject payloadJson = JWTParseUtil.jwtParser(tokenVerifyRequest).getRight();
        if (payloadJson.get("token") != null) {
            Map<String,Object> verifyResponseMap = new HashMap<>();
            verifyResponseMap.put("uid","5d142092ec5fa0ff72d51048290a44a3839ae290ed481c0c406fc6953a48e10a");
            verifyResponseMap.put("expired",System.currentTimeMillis() / 1000);
            Map<String,Object> headMap = new HashMap<>();
            headMap.put("ecode",0);
            headMap.put("edesc","");
            SSORequest ssoRequest = new SSORequest(headMap,verifyResponseMap,AgentComponent.AGENT_ID,AgentComponent.AGENT_KEY);
            String verifyResponseToken = ssoRequest.toString();
            System.err.println("token_verify=" + verifyResponseToken);
            return new ResponseEntity<>(verifyResponseToken, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @GetMapping(value = "/query",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> query(@RequestParam("query_request") final String queryRequest) throws UnsupportedEncodingException {
        Pair<JSONObject,JSONObject> pair = JWTParseUtil.jwtParser(queryRequest);
        System.err.println(JSONObject.toJSONString(pair, true));
        Map<String,Object> queryResponseMap = new HashMap<>();
        queryResponseMap.put("USER_IP","10.0.80.xx");
        queryResponseMap.put("CERT","xxxx");
        queryResponseMap.put("USER_ID","“xxxx”");
        queryResponseMap.put("CERT_SUBJECT_DN","xxx");
        queryResponseMap.put("CERT_SUBJECT_CN","test 370105197607083328");
        queryResponseMap.put("CERT_SUBJECT_CN_NAME","testuser");
        queryResponseMap.put("CERT_SUBJECT_CN_IDNUM","");
        queryResponseMap.put("CERT_ISSUER_DN","test");
        queryResponseMap.put("CERT_KEYTYPE","rsaEncryption");
        queryResponseMap.put("USER_ID_FORMAT","X509SubjectName");
        queryResponseMap.put("AUTH_SERVER","10.0.80.131");
        queryResponseMap.put("AUTH_TIME","2021-09-17 15:05:54");
        queryResponseMap.put("AUTH_METHOD","PKIWITHSIGN");
        queryResponseMap.put("USER_LOGIN_TIME","2021-09-17 15:05:54");
        queryResponseMap.put("AUTH_RESULT_NOTBEFORE","2021-09-17 15:05:54");
        queryResponseMap.put("CERT_SUBJECT_DN_EMAIL","zhangrm@koal.com");
        SSORequest ssoRequest = new SSORequest(queryResponseMap,AgentComponent.AGENT_ID, AgentComponent.AGENT_KEY);
        String token = ssoRequest.toString();
        return new ResponseEntity<>(token, HttpStatus.OK);
    }
}
